# gui/main_window.py
from __future__ import annotations
from typing import Optional
import os
import tkinter as tk
from tkinter import ttk
from .timer_tab import TimerTab
from .stats_tab import StatsTab


class MainWindow:
    """
    Root window + Notebook assembly. Keeps cross-tab wiring minimal.
    """

    def __init__(self, root: Optional[tk.Tk] = None) -> None:
        self.root = root or tk.Tk()
        self.root.title("计时器")
        self.root.minsize(700, 550)

        # Optional app icon: look for "计时器.png" next to timer_gui.py (back-compat)
        try:
            import timer_gui as _legacy

            icon_dir = os.path.dirname(getattr(_legacy, "__file__", ""))
            icon_path = os.path.join(icon_dir, "计时器.png")
            if os.path.exists(icon_path):
                img = tk.PhotoImage(file=icon_path)
                self.root.iconphoto(True, img)
        except Exception:
            pass

        self.notebook = ttk.Notebook(self.root)
        self.notebook.pack(fill=tk.BOTH, expand=True)
        style = ttk.Style()
        try:
            style.configure("TNotebook.Tab", padding=(50, 1))
        except Exception:
            pass

        # Tabs
        self.timer_tab = TimerTab(
            self.notebook, root=self.root, on_data_changed=self._on_data_changed
        )
        self.stats_tab = StatsTab(self.notebook)

        self.notebook.add(self.timer_tab.frame, text="计时")
        self.notebook.add(self.stats_tab.frame, text="统计")

        # Shortcuts
        self.root.bind("<Delete>", lambda e: self.timer_tab.delete_timer())
        self.root.protocol("WM_DELETE_WINDOW", self.on_closing)

    # ----- Cross-tab events -----
    def _on_data_changed(self) -> None:
        try:
            self.stats_tab.refresh()
        except Exception:
            pass

    def on_closing(self) -> None:
        # If TimerTab exposes any cleanup, call it here in the future
        self.root.destroy()

    def run(self) -> None:
        self.root.mainloop()
